import axios from "axios"
import getDynamicHeader from './request/header.js'
const Mock = require('mockjs')

/**
 * 正则转译
 * @param {*} url 
 * @returns 
 */
function createRegExp(url) {
    const escapedUrl = url.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const reg = new RegExp('^' + escapedUrl + '(\\?.*)?$');
    return reg;
}

function mockDone(cfg) {
    const { mockFilter } = cfg;
    cfg.baseURL = "/";
    cfg.url = `/mock${cfg.url}`;
    // 正则未能兼容get请求
    const rex = createRegExp(cfg.url);
    Mock.mock(rex, mockFilter);
}
const requestIns = axios.create({
    // baseURL: location.host +"/sjzt",
    baseURL: process.env.VUE_APP_API_BASE_URL,
    timeout: 90000
})


requestIns.interceptors.request.use((config) => {
    if (process.env.VUE_APP_MOCK === '1') {
        mockDone(config);
    }
    const headerParams = getDynamicHeader();
    Object.assign(config.headers, headerParams);
    return config;
});

requestIns.interceptors.response.use(function (response) {
    const { data = {} } = response;
    return data.data || {};
}, function (error) {
    return Promise.reject(error);
});

const request = requestIns
export { request };

